package com.farm.system.controller;

import com.farm.constant.MessageConstant;
import com.farm.entity.PageResult;
import com.farm.entity.Result;
import com.farm.entity.StatusCode;
import com.farm.system.pojo.User;
import com.farm.system.pojo.UserDTO;
import com.farm.system.service.UserService;
import com.farm.system.util.CookieUtil;
import com.farm.system.util.JwtUtil;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 用户控制层
 *
 * @author Chengfei
 * @date 2020/10/10
 */
@RestController
@RequestMapping("/user")
public class UserController {
    //cookie默认到期时间
    private static final Integer COOKIE_DEFAULT_MAXAGE = -1;
    //cookie关闭时间
    private static final Integer COOKIE_CLOSE_MAXAGE = 0;
    //用户的状态
    private static final String USER_FIRST_LOGIN = "2";
    private static final String USER_BAN_LOGIN = "0";

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询所有
     *
     * @return 用户集合
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<User> userList = userService.findAll();
        return new Result(true, StatusCode.OK, MessageConstant.SELECT_ALL_USER_SUCCESS, userList);
    }

    /**
     * 条件+分页查询
     *
     * @param page      页码
     * @param size      大小
     * @param searchMap 条件
     * @return 用户集合
     */
    @GetMapping("/findPageByCondition")
    public Result findPageByCondition(@RequestParam(name = "page", required = false, defaultValue = "1") Integer page,
                                      @RequestParam(name = "size", required = false, defaultValue = "10") Integer size,
                                      @RequestParam Map<String, Object> searchMap) {

        Page<User> pageList = userService.findPageByCondition(page, size, searchMap);
        PageResult pageResult = new PageResult(pageList.getTotal(), pageList.getResult());
        return new Result(true, StatusCode.OK, MessageConstant.SELECT_USER_SUCCESS, pageResult);
    }


    /**
     * 添加用户
     *
     * @param user    用户
     * @param roleIds 角色id数组
     * @return 无
     */
    @PostMapping("/add")
    public Result add(@RequestBody User user, @RequestParam Integer[] roleIds) {
        userService.add(user, roleIds);
        return new Result(true, StatusCode.OK, MessageConstant.ADD_USER_SUCCESS);
    }

    /**
     * 更新用户
     *
     * @param user    用户
     * @param roleIds 角色id数组
     * @return 无
     */
    @PutMapping("/update")
    public Result update(@RequestBody User user, @RequestParam Integer[] roleIds) {
        userService.update(user, roleIds);
        return new Result(true, StatusCode.OK, MessageConstant.UPDATE_USER_SUCCESS);
    }

    /**
     * 逻辑删除用户
     *
     * @param userId 用户id
     * @return 无
     */
    @DeleteMapping("/delete/{userId}")
    public Result delete(@PathVariable("userId") Integer userId) {
        userService.delete(userId);
        return new Result(true, StatusCode.OK, MessageConstant.DELETE_USER_SUCCESS);
    }

    /**
     * 恢复账号
     *
     * @param userId 用户id
     * @return
     */
    @PutMapping("/renew/{userId}")
    public Result renew(@PathVariable("userId") Integer userId) {
        userService.renew(userId);

        return new Result(true, StatusCode.OK, MessageConstant.RENEW_USER_SUCCESS);
    }


    /**
     * 重置密码
     *
     * @param userId 用户id
     * @return 无
     */
    @PutMapping("/resetPassword/{userId}")
    public Result resetPassword(@PathVariable("userId") Integer userId) {
        userService.resetPassword(userId);
        return new Result(true, StatusCode.OK, MessageConstant.RESET_USER_PASSWORD_SUCCESS);
    }

    /**
     * 登录
     * @
     * @return 用户
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody UserDTO userDTO, HttpServletResponse response) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        User user = userService.login(username, password);
        //判断是否登录成功
        if (user != null && !USER_BAN_LOGIN.equals(user.getStatus())) {
            //登录成功
            //生成jwt令牌存入redis
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), username, null);
            redisTemplate.opsForHash().put("token", username, token);

            //将用户名写入cookie
            CookieUtil.addCookie(response, "username", username, COOKIE_DEFAULT_MAXAGE);

            //判断是否初始登录
            if (USER_FIRST_LOGIN.equals(user.getStatus())) {
                return new Result<>(true, StatusCode.OK, MessageConstant.USER_FIRST_LOGIN_SUCCESS);
            }
            //登录成功
            return new Result<>(true, StatusCode.OK, MessageConstant.USER_LOGIN_SUCCESS);
        } else {
            //登录失败
            return new Result<>(false, StatusCode.ERROR, MessageConstant.USER_LOGIN_FAIL);
        }
    }

    /**
     * 登出
     *
     * @return
     */
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response) {
        //从cookie中读取用户名
        Map<String, String> map = CookieUtil.readCookie(request, "username");
        String username = map.get("username");
        if (username == null) {
            throw new RuntimeException(MessageConstant.USER_LOGOUT_FAIL);
        }
        //删除redis中token
        redisTemplate.opsForHash().delete("token", username);
        //删除cookie
        CookieUtil.addCookie(response, "username", "", COOKIE_CLOSE_MAXAGE);

        return new Result(true, StatusCode.OK, MessageConstant.USER_LOGOUT_SUCCESS);
    }

}
